//
//  ZPImageMagnification.m
//  Sport
//
//  Created by Cass on 2018/1/14.
//  Copyright © 2018年 Cass. All rights reserved.
//

#import "ZPImageMagnification.h"

@implementation ZPImageMagnification

//原始尺寸
static CGRect oldframe;
+(void)scanBigImageWithImageView:(UIImageView *)currentImageView alpha:(CGFloat)alpha{
    //当前imageview的图片
    UIImage *image = currentImageView.image;
    //当前视图
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //背景
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    //  当前imageview的原始尺寸->将像素currentImageview.bounds由currentImageview.bounds所在视图转换到目标视图window中，返回在目标视图window中的像素值
    oldframe = [currentImageView convertRect:currentImageView.bounds toView:window];
    [backgroundView setBackgroundColor:[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:alpha]];
    
    //此时视图不会显示
    [backgroundView setAlpha:0];
    //将所展示的imageView重新绘制到Window中
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:oldframe];
    [imageView setImage:image];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [imageView setTag:1024];
    [backgroundView addSubview:imageView];
    //将原始视图添加到背景视图
    [window addSubview:backgroundView];
    
    //添加点击事件同样是类方法，作用是再次点击回到初始大小
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImageView:)];
    [backgroundView addGestureRecognizer:tapGestureRecognizer];
    
    //动画放大嗦展示的ImageVIew
    [UIView animateWithDuration:0.4 animations:^{
        CGFloat y,width,height;
        y = ([UIScreen mainScreen].bounds.size.height - image.size.height*[UIScreen mainScreen].bounds.size.width / image.size.width) * 0.5;
        //宽度为屏幕宽度
        width = [UIScreen mainScreen].bounds.size.width;
        //高度根据图片宽高比设置
        if (image.size.width > 0) {
            height = image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width;
        }
        [imageView setFrame:CGRectMake(0, y, width, height)];
        //将视图展示出来
        [backgroundView setAlpha:1];
        
    } completion:^(BOOL finished) {
        
    }];
}

+ (void)hideImageView:(UITapGestureRecognizer *)tap{
    UIView *backgroundView = tap.view;
    //原始imageView
    UIImageView *imageView = [tap.view viewWithTag:1024];
    //恢复
    [UIView animateWithDuration:0.4 animations:^{
        [imageView setFrame:oldframe];
        [backgroundView setAlpha:0];
        
    } completion:^(BOOL finished) {
        //完成操作后,将背景视图删掉
        [backgroundView removeFromSuperview];
    }];
}
@end
